package pres.hdy.htmltopdf.config;

import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.itextpdf.text.DocumentException;

import freemarker.cache.TemplateLoader;
import pres.hdy.htmltopdf.inter.SimpleConfig;
import pres.hdy.htmltopdf.util.Time;

public class ItextRenderConfig implements SimpleConfig {
	private ITextRenderer iTextRenderer;

	public ItextRenderConfig() {
		// TODO Auto-generated constructor stub
		this(new ITextRenderer());
	}

	public ItextRenderConfig(ITextRenderer iTextRenderer) {
		// TODO Auto-generated constructor stub
		this.iTextRenderer = iTextRenderer;
	}

	@Override
	public void addFont(String path, String encoding, boolean embedded) {
		ITextFontResolver fontResolver = this.iTextRenderer.getFontResolver();
		try {
			fontResolver.addFont(path, encoding, embedded);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			System.out.println(Time.getNowTime() + ":" + path + " font not use!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void createPdf(Object url, String pdf) {
		try (BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(pdf))) {
			setDocument(url);
			this.iTextRenderer.layout();
			try {
				this.iTextRenderer.createPDF(o);
			} catch (DocumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public void setDocument(Object c) {
		if (c instanceof Document)
			this.iTextRenderer.setDocument((Document) c, null);
		else if (c instanceof String)
			this.iTextRenderer.setDocument((String) c);
	}

	@Override
	public void setTemplateLoader(TemplateLoader templateLoader) {

	}

	@Override
	public Document getDocument(String path, Object mapping) {
		return null;
	}

	@Override
	public void setEncoding(String encoding) {
		
	}

}
